<?php

use console\db\channels\TransferTableMigration;
use yii\db\Query;

/**
 * 文章和评论点赞转移
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300010_000009_t_cms_article_like extends TransferTableMigration {

    /**
     * @inheritdoc
     */
    public $sourceDb = 'olddb';

    /**
     * @inheritdoc
     */
    public function buildQuery() {
        return (new Query())->from('{{%' . $this->sourceTable . '}}')->where([
            'model' => [
                'article',
                'article_comment'
            ]
        ])->orderBy([
            'created_at' => SORT_ASC
        ]);
    }

    /**
     * @inheritdoc
     */
    public function validateTransfer(&$data) {
        if (!parent::validateTransfer($data)) {
            return false;
        }
        if ($data['model'] == 'article') {
            $article = (new Query)->from('{{%cms_article}}')->where([
                'id' => $data['model_id']
            ])->one();
            if (empty($article)) {
                return false;
            }
            $data['article_id'] = $article['id'];
            $data['comment_id'] = 0;
        } elseif ($data['model'] == 'article_comment') {
            $comment = (new Query)->from('{{%cms_article_comment}}')->where([
                'id' => $data['model_id']
            ])->one();
            if (empty($comment)) {
                return false;
            }
            $data['article_id'] = $comment['article_id'];
            $data['comment_id'] = $comment['id'];
        } else {
            return false;
        }
        return true;
    }

    /**
     * @inheritdoc
     */
    public function getTransferOptions() {
        return [
            'table' => [
                'cms_article_like' => 'ts_user_like',
            ],
            'columns' => [
                'article_id',
                'comment_id',
                'user_id',
                'created_at',
                'updated_at',
            ],
        ];
    }

}
